package controllers;

import com.github.binarywang.wxpay.bean.request.WxEntPayRequest;
import com.github.binarywang.wxpay.bean.result.WxEntPayResult;
import com.github.binarywang.wxpay.service.WxPayService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import models.helper.WxMpHelper;
import models.pay.SimulationPayData;
import models.weixin.WebUser;
import play.Logger;
import play.mvc.*;
import utils.DateUtil;

import java.util.Date;

public class AdminIndex extends Controller {

    public static void index() {
//        payToUser();
        sendTempTest();
        render();
    }
    public static void payToUser() {
        WebUser webUser = WebUser.findById(1l);
        Logger.info("WebUser : %s" , webUser);
        WxEntPayRequest wxEntPayRequest = SimulationPayData.wxEntPayInfo(webUser);
        WxPayService wxPayService = WxMpHelper.getWxPayService(webUser.weixinData);
        try {
            WxEntPayResult wxEntPayResult = wxPayService.entPay(wxEntPayRequest);
            if ("SUCCESS".equals(wxEntPayResult.getResultCode().toUpperCase())
                    && "SUCCESS".equals(wxEntPayResult.getReturnCode().toUpperCase())) {
                Logger.info("企业对个人付款成功！\n付款信息：\n" + wxEntPayResult.toString());
            } else {
                Logger.error("err_code: " + wxEntPayResult.getErrCode()
                        + "  err_code_des: " + wxEntPayResult.getErrCodeDes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void sendTempTest() {
        WebUser webUser = WebUser.findById(1l);
        WxMpService wxMpService = WxMpHelper.getWxMpService();
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(webUser.openId)
                .templateId("gxxid-84bNfJGZRYCEvKERu1fu-ZYolxJYM46qyF300")
                .build();
        templateMessage.getData().add(new WxMpTemplateData("first", "商户端发送模板消息测试", "#dbdbdb"));
        templateMessage.getData().add(new WxMpTemplateData("keyword1", "当前系统", "#dbdbdb"));
        templateMessage.getData().add(new WxMpTemplateData("keyword2", DateUtil.dateToString(new Date() , "yyyy-MM-dd HH:mm:ss"), "#dbdbdb"));
        templateMessage.getData().add(new WxMpTemplateData("remark", "商户端测试成功", "#dbdbdb"));
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            Logger.info("模板消息发送失败： %s" , e.getMessage());
            e.printStackTrace();
        }
    }


}